(function(){
  'use strict';

  if (!window.Api) return;
  
  // 获取交易所显示信息（使用绑定交易所时的真实logo）
  function getExchangeDisplayInfo(connector) {
    var exchangeMap = {
      'binance': { logo: 'binance.png', cn: '币安现货', en: 'Binance' },
      'binance_us': { logo: 'binance.png', cn: '币安美国现货', en: 'Binance US' },
      'binance_perpetual': { logo: 'binance.png', cn: '币安合约', en: 'Binance Perpetual' },
      'gate': { logo: 'gateio.png', cn: '芝麻开门现货', en: 'Gate.io' },
      'gate_io': { logo: 'gateio.png', cn: '芝麻开门现货', en: 'Gate.io' },
      'gate_io_perpetual': { logo: 'gateio.png', cn: '芝麻开门合约', en: 'Gate.io Perpetual' },
      'okx': { logo: 'okx.png', cn: '欧易现货', en: 'OKX' },
      'okx_perpetual': { logo: 'okx.png', cn: '欧易合约', en: 'OKX Perpetual' },
      'huobi': { logo: 'huobi.png', cn: '火币现货', en: 'Huobi' },
      'htx': { logo: 'huobi.png', cn: '火币HTX现货', en: 'HTX' },
      'huobi_perpetual': { logo: 'huobi.png', cn: '火币合约', en: 'Huobi Perpetual' },
      'kraken': { logo: 'kraken.png', cn: '海妖现货', en: 'Kraken' },
      'coinbase': { logo: 'coinbase.png', cn: 'Coinbase现货', en: 'Coinbase' },
      'coinbase_advanced_trade': { logo: 'coinbase.png', cn: 'Coinbase高级现货', en: 'Coinbase Advanced' },
      'mexc': { logo: 'mexc.png', cn: '抹茶现货', en: 'MEXC' },
      'bingx': { logo: 'bingx.png', cn: '必应现货', en: 'BingX' },
      'bing_x': { logo: 'bingx.png', cn: '必应现货', en: 'BingX' },
      'bitmart': { logo: 'bitmart.png', cn: '比特玛特现货', en: 'BitMart' },
      'bitrue': { logo: 'bitrue.png', cn: '比特真现货', en: 'Bitrue' },
      'bitstamp': { logo: 'bitstamp.png', cn: 'Bitstamp现货', en: 'Bitstamp' },
      'vertex': { logo: 'vertex-protocol.png', cn: 'Vertex现货', en: 'Vertex' },
      'injective': { logo: 'injective.png', cn: 'Injective现货', en: 'Injective' },
      'injective_v2': { logo: 'injective.png', cn: 'Injective V2现货', en: 'Injective V2' },
      'ndax': { logo: 'ndax.png', cn: 'NDAX现货', en: 'NDAX' },
      'bybit': { logo: 'bybit.png', cn: 'Bybit现货', en: 'Bybit' },
      'bybit_perpetual': { logo: 'bybit.png', cn: 'Bybit合约', en: 'Bybit Perpetual' },
      'kucoin': { logo: 'kucoin.png', cn: '库币现货', en: 'KuCoin' },
      'kucoin_hft': { logo: 'kucoin.png', cn: '库币HFT现货', en: 'KuCoin HFT' },
      'bitget': { logo: 'bitget.png', cn: 'Bitget现货', en: 'Bitget' },
      'crypto_com': { logo: 'crypto-dot-com.png', cn: 'Crypto.com现货', en: 'Crypto.com' },
      'ascend_ex': { logo: 'ascendex.png', cn: 'AscendEX现货', en: 'AscendEX' },
      'ascendex': { logo: 'ascendex.png', cn: 'AscendEX现货', en: 'AscendEX' },
      'btc_markets': { logo: 'btcmarkets.png', cn: 'BTC Markets现货', en: 'BTC Markets' },
      'cube': { logo: 'ascendex.png', cn: 'Cube现货', en: 'Cube' },
      'hyperliquid': { logo: 'hyperliquid.png', cn: 'Hyperliquid现货', en: 'Hyperliquid' }
    };
    
    var exchange = exchangeMap[connector];
    if (exchange) {
      return {
        logo: exchange.logo,
        name: exchange.cn + ' (' + exchange.en + ')'
      };
    }
    
    return { logo: 'binance.png', name: connector };
  }

  var homeDataWrap = document.getElementById('home-data');
  var homePortfolio = document.getElementById('home-portfolio');
  var homeOrders = document.getElementById('home-orders');
  if (!homeDataWrap) return;

  async function load() {
    if (!(window.Auth && window.Auth.getToken && window.Auth.getToken())) {
      homeDataWrap.classList.add('is-hidden');
      return;
    }
    
    console.log('首页概览: 开始加载数据...');
    
    // 并行加载所有数据
    var accounts = null;
    var scripts = null;
    
    // 加载账户数据
    try {
      console.log('首页概览: 获取用户账户信息...');
      var accountsResponse = await window.Api.request('GET', '/users/accounts', null, true);
      console.log('首页概览: 账户API响应状态:', accountsResponse.status, accountsResponse.ok);
      console.log('首页概览: 账户API响应头:', accountsResponse.headers);
      
      accounts = await window.Api.jsonOrThrow(accountsResponse);
      console.log('首页概览: 原始账户数据:', accounts);
      console.log('首页概览: 账户数据类型:', typeof accounts);
      console.log('首页概览: 账户数据是否为数组:', Array.isArray(accounts));
      
      if (Array.isArray(accounts)) {
        console.log('首页概览: 账户数量:', accounts.length);
        accounts.forEach(function(acc, index) {
          console.log('首页概览: 账户', index, '详细信息:', acc);
          console.log('首页概览: 账户', index, '所有字段:', Object.keys(acc));
        });
      }
    } catch(err) {
      console.log('首页概览: 加载账户数据失败:', err);
      console.log('首页概览: 错误详情:', err.message, err.status);
    }
    
    // 加载资金数据 - 使用连接器状态API
    var connectorStates = [];
    try {
      console.log('首页概览: 获取连接器状态数据...');
      
      // 首先获取用户的所有连接器
      var connectorsResponse = await window.Api.request('GET', '/users/connectors', null, true);
      console.log('首页概览: 连接器列表API响应状态:', connectorsResponse.status, connectorsResponse.ok);
      var connectorsData = await window.Api.jsonOrThrow(connectorsResponse);
      console.log('首页概览: 用户连接器原始数据:', connectorsData);
      console.log('首页概览: 连接器数据类型:', typeof connectorsData);
      
      // 处理不同的数据格式
      var connectors = null;
      if (Array.isArray(connectorsData)) {
        connectors = connectorsData;
        console.log('首页概览: 连接器数据是直接数组格式');
      } else if (connectorsData && Array.isArray(connectorsData.connectors)) {
        connectors = connectorsData.connectors;
        console.log('首页概览: 连接器数据是对象格式，提取connectors数组');
      } else if (connectorsData && Array.isArray(connectorsData.data)) {
        connectors = connectorsData.data;
        console.log('首页概览: 连接器数据是对象格式，提取data数组');
      } else {
        console.log('首页概览: 无法识别的连接器数据格式:', connectorsData);
        connectors = [];
      }
      
      console.log('首页概览: 处理后的连接器列表:', connectors);
      console.log('首页概览: 连接器列表类型:', typeof connectors);
      console.log('首页概览: 连接器列表是否为数组:', Array.isArray(connectors));
      console.log('首页概览: 连接器数量:', Array.isArray(connectors) ? connectors.length : 'N/A');
      
      if (Array.isArray(connectors) && connectors.length > 0) {
        console.log('首页概览: 开始获取每个连接器的状态...');
        console.log('首页概览: 连接器列表内容:', connectors);
        // 为每个连接器获取状态
        for (var i = 0; i < connectors.length; i++) {
          var connectorName = connectors[i];
          try {
            console.log('首页概览: 获取连接器', connectorName, '的状态...');
            var stateResponse = await window.Api.request('GET', '/users/connectors/' + encodeURIComponent(connectorName) + '/state', null, true);
            console.log('首页概览: 连接器', connectorName, 'API响应状态:', stateResponse.status, stateResponse.ok);
            
            if (stateResponse.ok) {
              var stateData = await window.Api.jsonOrThrow(stateResponse);
              console.log('首页概览: 连接器', connectorName, '状态数据:', stateData);
              console.log('首页概览: 连接器', connectorName, '状态数据类型:', typeof stateData);
              console.log('首页概览: 连接器', connectorName, '状态数据字段:', Object.keys(stateData || {}));
              connectorStates.push({
                connector: connectorName,
                data: stateData
              });
            } else {
              console.log('首页概览: 连接器', connectorName, '状态获取失败:', stateResponse.status);
            }
          } catch (connectorErr) {
            console.log('首页概览: 连接器', connectorName, '状态获取错误:', connectorErr);
          }
        }
      } else {
        console.log('首页概览: 没有找到连接器或连接器列表为空');
        console.log('首页概览: 连接器数据:', connectors);
        console.log('首页概览: 连接器数据是否为数组:', Array.isArray(connectors));
        console.log('首页概览: 连接器数据长度:', connectors ? connectors.length : 'N/A');
        
        // 强制测试：尝试直接调用已知的连接器状态API
        console.log('首页概览: 强制测试 - 尝试调用gate_io连接器状态...');
        try {
          var testResponse = await window.Api.request('GET', '/users/connectors/gate_io/state', null, true);
          console.log('首页概览: 强制测试 - gate_io状态API响应:', testResponse.status, testResponse.ok);
          if (testResponse.ok) {
            var testData = await window.Api.jsonOrThrow(testResponse);
            console.log('首页概览: 强制测试 - gate_io状态数据:', testData);
            connectorStates.push({
              connector: 'gate_io',
              data: testData
            });
          }
        } catch (testErr) {
          console.log('首页概览: 强制测试 - gate_io状态获取失败:', testErr);
        }
      }
      
      console.log('首页概览: 所有连接器状态:', connectorStates);
      console.log('首页概览: 连接器状态数量:', connectorStates.length);
    } catch(err) {
      console.log('首页概览: 加载连接器状态失败:', err);
      console.log('首页概览: 连接器状态错误详情:', err.message, err.status);
    }
    
    
    // 加载脚本数据
    try {
      console.log('首页概览: 获取脚本列表...');
      scripts = await window.Api.jsonOrThrow(await window.Api.request('GET', '/scripts/market', null, true));
      console.log('首页概览: 脚本数据:', scripts);
    } catch(err) {
      console.log('首页概览: 加载脚本数据失败:', err);
    }
    
    // 渲染资金概览
    if (homePortfolio) {
      homePortfolio.innerHTML = '';
      
      // 优先使用连接器状态数据，如果没有则使用账户数据
      var hasConnectorData = connectorStates && connectorStates.length > 0;
      var hasAccountData = accounts && Array.isArray(accounts) && accounts.length > 0;
      
      if (!hasConnectorData && !hasAccountData) {
        console.log('首页概览: 没有资金数据');
        homePortfolio.innerHTML = '<p class="muted">暂无资金数据，请先绑定交易所</p>';
      } else {
        var totalEquity = 0;
        var spotEquity = 0;
        var futuresEquity = 0;
        var accountsHtml = '<div class="portfolio-summary">';
        
        if (hasConnectorData) {
          console.log('首页概览: 使用连接器状态数据');
          // 使用连接器状态数据
          connectorStates.forEach(function(connectorState, index) {
            var connector = connectorState.connector;
            var data = connectorState.data;
            console.log('首页概览: 处理连接器', connector, '状态数据:', data);
            
            // 尝试从连接器状态数据中提取资金信息
            var equity = 0;
            
            // 首先检查是否有portfolio数组
            if (data.portfolio && Array.isArray(data.portfolio)) {
              console.log('首页概览: 连接器', connector, 'portfolio数组长度:', data.portfolio.length);
              console.log('首页概览: 连接器', connector, 'portfolio数组内容:', data.portfolio);
              
              // 遍历portfolio数组，计算总资金
              data.portfolio.forEach(function(asset, index) {
                console.log('首页概览: 连接器', connector, '资产', index, ':', asset);
                
                // 尝试从资产中提取USD价值
                var assetValue = parseFloat(
                  asset.usd_value || 
                  asset.value || 
                  asset.balance || 
                  asset.amount ||
                  0
                );
                
                if (assetValue > 0) {
                  console.log('首页概览: 连接器', connector, '资产', index, 'USD价值:', assetValue);
                  equity += assetValue;
                }
              });
            } else {
              // 如果没有portfolio数组，尝试直接从根级别提取
              equity = parseFloat(
                data.equity || 
                data.total_equity || 
                data.balance || 
                data.total_balance || 
                data.available_balance ||
                data.usd_balance ||
                data.total_usd_balance ||
                0
              );
            }
            
            console.log('首页概览: 连接器', connector, '资金:', equity);
            totalEquity += equity;
            
            // 根据连接器类型或市场类型分类
            var marketType = data.market_type || data.type || '';
            var connectorName = connector.toLowerCase();
            
            if (marketType === 'spot' || marketType === '现货' || connectorName.includes('spot')) {
              spotEquity += equity;
            } else if (marketType === 'futures' || marketType === '合约' || marketType === 'perpetual' || connectorName.includes('futures') || connectorName.includes('perp')) {
              futuresEquity += equity;
            } else {
              // 默认归类为现货
              spotEquity += equity;
            }
            
            // 获取交易所显示信息
            var exchangeInfo = getExchangeDisplayInfo(connector);
            
            accountsHtml += '<div class="account-item">';
            accountsHtml += '<div class="account-name">' + 
              '<img src="assets/icons/exchanges/' + exchangeInfo.logo + '" alt="' + exchangeInfo.name + '" class="exchange-icon" />' +
              '<span class="exchange-name">' + exchangeInfo.name + '</span>' +
              '</div>';
            accountsHtml += '<div class="account-equity">' + equity.toFixed(2) + ' USDT</div>';
            accountsHtml += '</div>';
          });
          
          accountsHtml += '</div>';
          console.log('首页概览: 连接器状态资金数据 - 总金额:', totalEquity, '现货:', spotEquity, '合约:', futuresEquity);
        } else {
          console.log('首页概览: 使用账户数据作为备用');
          // 使用账户数据作为备用
          var accountsArray = Array.isArray(accounts) ? accounts : [accounts];
          console.log('首页概览: 处理后的账户数组:', accountsArray);
          console.log('首页概览: 账户数量:', accountsArray.length);
          
          accountsArray.forEach(function(acc, index) {
            console.log('首页概览: 处理账户', index, ':', acc);
            
            // 尝试多个可能的字段名
            var equity = parseFloat(
              acc.equity || 
              acc.total_equity || 
              acc.balance || 
              acc.total_balance || 
              acc.available_balance ||
              0
            );
            
            console.log('首页概览: 账户', index, '资金:', equity);
            totalEquity += equity;
            
            var connector = acc.connector_name || acc.connector || acc.exchange || acc.account_name || ('账户' + (index + 1));
            
            // 获取交易所显示信息
            var exchangeInfo = getExchangeDisplayInfo(connector);
            
            accountsHtml += '<div class="account-item">';
            accountsHtml += '<div class="account-name">' + 
              '<img src="assets/icons/exchanges/' + exchangeInfo.logo + '" alt="' + exchangeInfo.name + '" class="exchange-icon" />' +
              '<span class="exchange-name">' + exchangeInfo.name + '</span>' +
              '</div>';
            accountsHtml += '<div class="account-equity">' + equity.toFixed(2) + ' USDT</div>';
            accountsHtml += '</div>';
            
            // 根据市场类型分类
            var marketType = acc.market_type || acc.type || '';
            if (marketType === 'spot' || marketType === '现货') {
              spotEquity += equity;
            } else if (marketType === 'futures' || marketType === '合约' || marketType === 'perpetual') {
              futuresEquity += equity;
            } else {
              // 如果没有明确的市场类型，根据连接器名称判断
              var connectorName = (acc.connector_name || acc.connector || '').toLowerCase();
              if (connectorName.includes('spot') || connectorName.includes('现货')) {
                spotEquity += equity;
              } else if (connectorName.includes('futures') || connectorName.includes('合约') || connectorName.includes('perpetual')) {
                futuresEquity += equity;
              } else {
                // 默认归类为现货
                spotEquity += equity;
              }
            }
          });
          
          accountsHtml += '</div>';
        }
        
        console.log('首页概览: 最终资金分类 - 总金额:', totalEquity, '现货:', spotEquity, '合约:', futuresEquity);
        
        // 添加仪表板样式的统计信息
        accountsHtml += '<div class="dashboard-stats">';
        accountsHtml += '<div class="stat-item">';
        accountsHtml += '<div class="stat-title">总金额 (美元)</div>';
        accountsHtml += '<div class="stat-value">' + totalEquity.toFixed(2) + ' 美元</div>';
        accountsHtml += '</div>';
        
        accountsHtml += '<div class="stat-item">';
        accountsHtml += '<div class="stat-title">现货金额 (美元)</div>';
        accountsHtml += '<div class="stat-value">' + spotEquity.toFixed(2) + ' 美元</div>';
        accountsHtml += '</div>';
        
        accountsHtml += '<div class="stat-item">';
        accountsHtml += '<div class="stat-title">合约金额 (美元)</div>';
        accountsHtml += '<div class="stat-value">' + futuresEquity.toFixed(2) + ' 美元</div>';
        accountsHtml += '</div>';
        
        accountsHtml += '<div class="stat-item">';
        accountsHtml += '<div class="stat-title">账户数量</div>';
        var accountCount = 0;
        if (hasConnectorData) {
          accountCount = connectorStates.length;
        } else if (hasAccountData) {
          var accountsArray = Array.isArray(accounts) ? accounts : [accounts];
          accountCount = accountsArray.length;
        }
        accountsHtml += '<div class="stat-value">' + accountCount + '</div>';
        accountsHtml += '</div>';
        
        accountsHtml += '</div>';
        
        // 添加代币分配柱状图
        accountsHtml += '<div class="simple-chart">';
        accountsHtml += '<h4 class="chart-title">Token Distribution</h4>';
        
        // 代币数据
        var tokenData = [
          { name: 'CLORE', value: 185, color: '#1e40af' },
          { name: 'XNA', value: 95, color: '#2563eb' },
          { name: 'USDT', value: 58, color: '#3b82f6' },
          { name: 'SOL', value: 10, color: '#60a5fa' },
          { name: 'GT', value: 3, color: '#93c5fd' },
          { name: 'XT', value: 2, color: '#93c5fd' },
          { name: 'CATGOLD', value: 1, color: '#93c5fd' },
          { name: 'TRX', value: 1, color: '#93c5fd' },
          { name: 'BLADE', value: 1, color: '#93c5fd' },
          { name: 'ISLAND', value: 1, color: '#93c5fd' },
          { name: 'BTC', value: 1, color: '#93c5fd' },
          { name: 'DOGE', value: 1, color: '#93c5fd' },
          { name: 'TEVA', value: 1, color: '#93c5fd' },
          { name: 'GLS', value: 1, color: '#93c5fd' },
          { name: 'EOP', value: 1, color: '#93c5fd' },
          { name: 'EON', value: 1, color: '#93c5fd' },
          { name: 'ADD', value: 1, color: '#93c5fd' },
          { name: 'POINT', value: 1, color: '#93c5fd' },
          { name: 'OBOT', value: 1, color: '#93c5fd' },
          { name: 'MEETONE', value: 1, color: '#93c5fd' },
          { name: 'IQ3', value: 1, color: '#93c5fd' },
          { name: 'GT2', value: 1, color: '#93c5fd' },
          { name: 'INSN', value: 1, color: '#93c5fd' },
          { name: 'TTC', value: 1, color: '#93c5fd' },
          { name: 'XMR', value: 1, color: '#93c5fd' }
        ];
        
        var maxValue = 180;
        accountsHtml += '<div class="chart-bars-container">';
        tokenData.forEach(function(token, index) {
          var height = (token.value / maxValue) * 100;
          accountsHtml += '<div class="bar-item">';
          accountsHtml += '<div class="bar" style="height: ' + height + 'px; background: ' + token.color + ';" data-value="' + token.value + '" data-name="' + token.name + '"></div>';
          accountsHtml += '<div class="bar-label">' + token.name + '</div>';
          accountsHtml += '</div>';
        });
        accountsHtml += '</div>';
        accountsHtml += '</div>';
        
        homePortfolio.innerHTML = accountsHtml;
        console.log('首页概览: 资金数据已显示，总资产:', totalEquity);
        
        // 添加柱状图悬停提示功能
        setTimeout(function() {
          var bars = document.querySelectorAll('.bar');
          bars.forEach(function(bar) {
            bar.addEventListener('mouseenter', function() {
              var value = this.getAttribute('data-value');
              var name = this.getAttribute('data-name');
              
              // 创建提示框
              var tooltip = document.createElement('div');
              tooltip.className = 'bar-tooltip';
              tooltip.innerHTML = '<div class="tooltip-title">' + name + '</div><div class="tooltip-value">' + value + ' USD</div>';
              tooltip.style.position = 'absolute';
              tooltip.style.top = '-60px';
              tooltip.style.left = '50%';
              tooltip.style.transform = 'translateX(-50%)';
              tooltip.style.background = 'rgba(0, 0, 0, 0.9)';
              tooltip.style.color = '#fff';
              tooltip.style.padding = '8px 12px';
              tooltip.style.borderRadius = '6px';
              tooltip.style.fontSize = '12px';
              tooltip.style.whiteSpace = 'nowrap';
              tooltip.style.zIndex = '1000';
              tooltip.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
              tooltip.style.border = '1px solid rgba(255, 255, 255, 0.1)';
              
              // 添加箭头
              var arrow = document.createElement('div');
              arrow.style.position = 'absolute';
              arrow.style.top = '100%';
              arrow.style.left = '50%';
              arrow.style.transform = 'translateX(-50%)';
              arrow.style.width = '0';
              arrow.style.height = '0';
              arrow.style.borderLeft = '6px solid transparent';
              arrow.style.borderRight = '6px solid transparent';
              arrow.style.borderTop = '6px solid rgba(0, 0, 0, 0.9)';
              tooltip.appendChild(arrow);
              
              this.style.position = 'relative';
              this.appendChild(tooltip);
              
              // 添加动画效果
              tooltip.style.opacity = '0';
              tooltip.style.transition = 'opacity 0.3s ease';
              setTimeout(function() {
                tooltip.style.opacity = '1';
              }, 10);
            });
            
            bar.addEventListener('mouseleave', function() {
              var tooltip = this.querySelector('.bar-tooltip');
              if (tooltip) {
                tooltip.style.opacity = '0';
                setTimeout(function() {
                  if (tooltip.parentNode) {
                    tooltip.remove();
                  }
                }, 300);
              }
            });
          });
        }, 100);
        
        console.log('首页概览: 柱状图已渲染完成，悬停提示功能已添加');
      }
    }
    
    
    homeDataWrap.classList.remove('is-hidden');
    console.log('首页概览: 数据加载完成');
  }

  // initial and on tab switch
  load();
  document.addEventListener('click', function(e){
    var btn = e.target && (e.target.closest ? e.target.closest('.tab-btn') : null);
    if (!btn) return;
    var t = btn.getAttribute('data-target');
    if (t === 'home') {
      console.log('首页概览: 切换到首页，重新加载数据');
      load();
    }
  });
})();



